import { Tip } from 'beeshell';
import { getToken } from '../service/token';
import { messageStore } from '../store/messageStore';
import Http from '../service/http';
import requestCheck from './RequestCheckUtil';

class WebSocketUtil {
  static getSingleton() {
    if (!this.instance) {
      this.instance = new WebSocket('ws://202.120.40.87:42163/websocket');
    }
    return this.instance;
  }

  static clear() {
    if (this.instance) {
      this.instance = null;
    }
  }

  static initWebSocket() {
    const websocket = WebSocketUtil.getSingleton();
    websocket.onopen = async () => {
      const token = await getToken();
      websocket.send(token);
      const res = await Http.getUnreadMessage();
      const { setUnReadNum } = messageStore;
      const callback = ({ unread }) => {
        setUnReadNum(unread.length);
      };
      requestCheck(res, callback);
    };
    websocket.onerror = () => {
    };
    websocket.onmessage = () => {
      Tip.show('您有消息未读');
      const { setRefresh } = messageStore;
      setRefresh();
    };
    websocket.onclose = () => {
      if (websocket.getSingleton) {
        websocket.getSingleton.close();
      }
    };
  }

  static closeWebSocket() {
    const websocket = WebSocketUtil.getSingleton();
    websocket.close();
  }
}

export default WebSocketUtil;
